using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Application.Dtos;
using TenantManagementService.Monitoring;

namespace TenantManagementService.Controllers
{
    /// <summary>
    /// 监控管理控制器
    /// </summary>
    [ApiController]
    [Route("api/monitoring")]
    [RemoteService]
    public class MonitoringController : AbpControllerBase
    {
        private readonly IMonitoringService _monitoringService;

        public MonitoringController(IMonitoringService monitoringService)
        {
            _monitoringService = monitoringService;
        }

        /// <summary>
        /// 记录监控指标
        /// </summary>
        [HttpPost("metrics")]
        public async Task RecordMetricAsync([FromBody] RecordMetricInput input)
        {
            await _monitoringService.RecordMetricAsync(
                input.MetricName,
                input.Value,
                input.Dimensions,
                input.TenantId
            );
        }

        /// <summary>
        /// 批量记录监控指标
        /// </summary>
        [HttpPost("metrics/batch")]
        public async Task RecordMetricsAsync([FromBody] List<MetricRecordInput> metrics)
        {
            await _monitoringService.RecordMetricsAsync(metrics);
        }

        /// <summary>
        /// 获取指标值
        /// </summary>
        [HttpGet("metrics/{metricName}/value")]
        public async Task<decimal?> GetMetricValueAsync(
            [FromRoute] string metricName,
            [FromQuery] DateTime? startTime = null,
            [FromQuery] DateTime? endTime = null,
            [FromQuery] string? dimensions = null,
            [FromQuery] Guid? tenantId = null)
        {
            Dictionary<string, string>? dimensionDict = null;
            if (!string.IsNullOrWhiteSpace(dimensions))
            {
                // 简单的键值对解析，格式：key1=value1,key2=value2
                dimensionDict = new Dictionary<string, string>();
                foreach (var pair in dimensions.Split(','))
                {
                    var kv = pair.Split('=', 2);
                    if (kv.Length == 2)
                    {
                        dimensionDict[kv[0].Trim()] = kv[1].Trim();
                    }
                }
            }

            return await _monitoringService.GetMetricValueAsync(metricName, startTime, endTime, dimensionDict, tenantId);
        }

        /// <summary>
        /// 获取指标历史数据
        /// </summary>
        [HttpGet("metrics/{metricName}/history")]
        public async Task<List<MetricDataPoint>> GetMetricHistoryAsync(
            [FromRoute] string metricName,
            [FromQuery] DateTime startTime,
            [FromQuery] DateTime endTime,
            [FromQuery] string? dimensions = null,
            [FromQuery] Guid? tenantId = null)
        {
            Dictionary<string, string>? dimensionDict = null;
            if (!string.IsNullOrWhiteSpace(dimensions))
            {
                dimensionDict = new Dictionary<string, string>();
                foreach (var pair in dimensions.Split(','))
                {
                    var kv = pair.Split('=', 2);
                    if (kv.Length == 2)
                    {
                        dimensionDict[kv[0].Trim()] = kv[1].Trim();
                    }
                }
            }

            return await _monitoringService.GetMetricHistoryAsync(metricName, startTime, endTime, dimensionDict, tenantId);
        }

        /// <summary>
        /// 获取租户使用统计
        /// </summary>
        [HttpGet("tenants/{tenantId}/usage-statistics")]
        public async Task<TenantUsageStatistics> GetTenantUsageStatisticsAsync(
            [FromRoute] Guid tenantId,
            [FromQuery] DateTime? startTime = null,
            [FromQuery] DateTime? endTime = null)
        {
            return await _monitoringService.GetTenantUsageStatisticsAsync(tenantId, startTime, endTime);
        }

        /// <summary>
        /// 获取所有租户概览统计
        /// </summary>
        [HttpGet("tenants/overview-statistics")]
        public async Task<TenantsOverviewStatistics> GetTenantsOverviewStatisticsAsync()
        {
            return await _monitoringService.GetTenantsOverviewStatisticsAsync();
        }

        /// <summary>
        /// 获取租户资源使用情况
        /// </summary>
        [HttpGet("tenants/resource-usage")]
        public async Task<List<TenantResourceUsage>> GetTenantResourceUsageAsync([FromQuery] List<Guid>? tenantIds = null)
        {
            return await _monitoringService.GetTenantResourceUsageAsync(tenantIds);
        }

        /// <summary>
        /// 检查告警规则
        /// </summary>
        [HttpPost("alert-rules/check")]
        public async Task CheckAlertRulesAsync()
        {
            await _monitoringService.CheckAlertRulesAsync();
        }

        /// <summary>
        /// 创建告警规则
        /// </summary>
        [HttpPost("alert-rules")]
        public async Task<AlertRuleDto> CreateAlertRuleAsync([FromBody] CreateAlertRuleInput input)
        {
            return await _monitoringService.CreateAlertRuleAsync(input);
        }

        /// <summary>
        /// 更新告警规则
        /// </summary>
        [HttpPut("alert-rules/{id}")]
        public async Task<AlertRuleDto> UpdateAlertRuleAsync(
            [FromRoute] Guid id,
            [FromBody] UpdateAlertRuleInput input)
        {
            return await _monitoringService.UpdateAlertRuleAsync(id, input);
        }

        /// <summary>
        /// 删除告警规则
        /// </summary>
        [HttpDelete("alert-rules/{id}")]
        public async Task DeleteAlertRuleAsync([FromRoute] Guid id)
        {
            await _monitoringService.DeleteAlertRuleAsync(id);
        }

        /// <summary>
        /// 获取告警规则列表
        /// </summary>
        [HttpGet("alert-rules")]
        public async Task<PagedResultDto<AlertRuleDto>> GetAlertRulesAsync([FromQuery] GetAlertRulesInput input)
        {
            return await _monitoringService.GetAlertRulesAsync(input);
        }

        /// <summary>
        /// 获取活跃告警列表
        /// </summary>
        [HttpGet("alerts/active")]
        public async Task<PagedResultDto<AlertDto>> GetActiveAlertsAsync([FromQuery] GetActiveAlertsInput input)
        {
            return await _monitoringService.GetActiveAlertsAsync(input);
        }

        /// <summary>
        /// 处理告警
        /// </summary>
        [HttpPost("alerts/{id}/handle")]
        public async Task<AlertDto> HandleAlertAsync(
            [FromRoute] Guid id,
            [FromBody] HandleAlertInput input)
        {
            return await _monitoringService.HandleAlertAsync(id, input);
        }

        /// <summary>
        /// 忽略告警
        /// </summary>
        [HttpPost("alerts/{id}/ignore")]
        public async Task<AlertDto> IgnoreAlertAsync(
            [FromRoute] Guid id,
            [FromBody] IgnoreAlertInput input)
        {
            return await _monitoringService.IgnoreAlertAsync(id, input.Reason);
        }

        /// <summary>
        /// 获取告警统计
        /// </summary>
        [HttpGet("alerts/statistics")]
        public async Task<AlertStatistics> GetAlertStatisticsAsync(
            [FromQuery] DateTime? startTime = null,
            [FromQuery] DateTime? endTime = null,
            [FromQuery] Guid? tenantId = null)
        {
            return await _monitoringService.GetAlertStatisticsAsync(startTime, endTime, tenantId);
        }

        /// <summary>
        /// 获取系统健康状态
        /// </summary>
        [HttpGet("health/status")]
        public async Task<SystemHealthStatus> GetSystemHealthStatusAsync()
        {
            return await _monitoringService.GetSystemHealthStatusAsync();
        }
    }

    /// <summary>
    /// 记录指标输入
    /// </summary>
    public class RecordMetricInput
    {
        /// <summary>
        /// 指标名称
        /// </summary>
        public string MetricName { get; set; } = string.Empty;

        /// <summary>
        /// 指标值
        /// </summary>
        public decimal Value { get; set; }

        /// <summary>
        /// 维度
        /// </summary>
        public Dictionary<string, string>? Dimensions { get; set; }

        /// <summary>
        /// 租户ID
        /// </summary>
        public Guid? TenantId { get; set; }
    }

    /// <summary>
    /// 忽略告警输入
    /// </summary>
    public class IgnoreAlertInput
    {
        /// <summary>
        /// 忽略原因
        /// </summary>
        public string Reason { get; set; } = string.Empty;
    }
}